//
//  YGHomeViewController.swift
//  sinaWeiBoGui
//
//  Created by liyonggui on 16/5/9.
//  Copyright © 2016年 liyonggui. All rights reserved.
//

import UIKit

import SVPullToRefresh

class YGHomeViewController: YGBasicViewController {
    
    // MARK: - 属性
    /// cell的重用标识
    private let reuseIndentifier = "cell"
    
    /// 提示label的高度
    private let tipLabelHeight: CGFloat = 44
    
    
    /// 微博模型数组
    var statuses:[YGStatus]? {
        didSet {
            YGPrint(items: "当前总共有\(statuses?.count)条微博")
            // 刷新
            self.tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // 没有登录，就直接返回
        if !YGUserAccountViewModel.sharedInstance.isUserLogin {
            return
        }
        
        setupNavigationBar()
        
        prepareTableView()
        
        // 添加下拉刷新提示label
        navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)

    }
    
    /// 设置tableView相关内容
    private func prepareTableView() {
        // MARK: - 注册cell
        tableView.registerClass(YGStatusCell.self, forCellReuseIdentifier: reuseIndentifier)
        
        // 设置cell的预估行高
        tableView.estimatedRowHeight = 88
        // 根据cell的约束自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        
        // 取消cell的分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        // 添加下拉刷新控件
        tableView.addSubview(pullDownToRefreshControl)
        
        // 监听下拉刷新控件进入刷新状态
        pullDownToRefreshControl.pullDownToRefreshingCallBack = { () -> () in
           // 加载微博数据
            self.loadNewStatuses()
        }
        
        // 主动进入刷新状态
        pullDownToRefreshControl.beginRefreshing()
        
//        // MARK: - 上拉加载更多
//        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
//            //            YGPrint(items: "上拉加载更多")
//            self.loadMoreStatuses()
//        }
    }
    
    /// 加载更多微博数据
    private func loadMoreStatuses() {
        
        let max_id = self.statuses?.last?.id ?? 0
        YGStatusViewModel.sharedInstance.loadStatus(0, max_id: max_id) { (statuses, error) -> () in
            // 上拉加载控件停止动画
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil {
                YGPrint(items: "上拉加载微博出错了")
                return
            }
            
            let count = statuses?.count ?? 0
            if count == 0 {
                YGPrint(items: "上拉没有加载到数据")
                return
            }
            
            YGPrint(items: "上拉加载了\(count)条微博数据")
            // 加载的数据拼接到原有数组后面
            self.statuses = self.statuses! + statuses!
        }
        
    }
    
    // MARK: - 获取微博数据
    /// 获取新的微博数据
    private func loadNewStatuses() {
        // 获取数组最前面，ID最大的
        let since_id = self.statuses?.first?.id ?? 0
        // 加载微博数据
        YGStatusViewModel.sharedInstance.loadStatus(since_id, max_id: 0) { (statuses, error) -> () in
            // 结束下拉刷新控件
            self.pullDownToRefreshControl.endRefreshing()
            
            if error != nil {
                YGPrint(items: "请求微博数据失败 : \(error)")
                return
            }
            
            let count = statuses?.count ?? 0
            YGPrint(items: "获取到了\(count)条微博数据")
            
            // 判断是下拉状态才显示提示label
            if since_id > 0 {
                self.showTipLabel(count)
            }
            
            if count == 0 {
                // 没有加载到新数据
                return
            }
            
            if since_id == 0 {
                // 赋值给属性,直接加载20条微博
                self.statuses = statuses
                
                // MARK: - 上拉加载更多
                self.tableView.addInfiniteScrollingWithActionHandler { () -> Void in
                    //            YGPrint(items: "上拉加载更多")
                    self.loadMoreStatuses()
                }
                
            } else {
                self.statuses = statuses! + self.statuses!
            }
        }
    }
    
    // MARK: - 下拉刷新提示label
    /// 设置下拉刷新提示label
    private func showTipLabel(count: Int) {
        let text = count == 0 ? "没有新的微博" : "加载了\(count)条新微博"
        tipLabel.text = text
        
        // 获取layer上的所有核心动画
        let anim = self.tipLabel.layer.animationKeys()
        if anim != nil {
            YGPrint(items: "移除\(anim)")
            self.tipLabel.layer.removeAllAnimations()
        }
        
        let duration = 0.75
        UIView.animateWithDuration(duration, animations: { () -> Void in
            self.tipLabel.frame.origin.y = self.tipLabelHeight
            }) { (_) -> Void in
                // 延迟退回去的动画
                UIView.animateWithDuration(duration, delay: 1, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                    self.tipLabel.frame.origin.y = -64
                    }, completion: nil)
        }
    }
    
    /// 设置导航栏
    private func setupNavigationBar() {
        // 二维码
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: "didClickFriendsearch")
        // 搜索
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action: "didClickPop")
        
        // 设置标题视图
        
        let name = YGUserAccountViewModel.sharedInstance.userAccount?.screen_name ?? "未知名称"
        
        let button = YGHomeTitleButton()
        
        button.setTitle(name, forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(16)
        button.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal)
        button.addTarget(self, action: "didClickTitleView:", forControlEvents: UIControlEvents.TouchUpInside)
        
        button.sizeToFit()
        
        navigationItem.titleView = button
    }
    
    // MARK: - 点击事件
    func didClickTitleView(button: UIButton) {
        // 修改按钮的状态
        button.selected = !button.selected
        
        UIView.animateWithDuration(0.25) { () -> Void in
            let temp = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.001)) : CGAffineTransformIdentity
            button.imageView?.transform = temp
        }
    }
    
    /// 朋友搜索
    func didClickFriendsearch() {
        YGPrint(items: "点击了左边->朋友搜索")
    }
    
    /// 二维码
    func didClickPop() {
        YGPrint(items: "点击了右边->二维码")
    }
    
    // MARK: - 懒加载
    /// 下拉刷新控件
    private lazy var pullDownToRefreshControl:YGPullDownToRefreshControl = YGPullDownToRefreshControl()
    
    /// 下拉提示的label
    private lazy var tipLabel: UILabel = {
        let label = UILabel()
        
        // 设置属性
        label.backgroundColor = UIColor.orangeColor()
        label.font = UIFont.systemFontOfSize(18)
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
        
        label.frame = CGRect(x: 0, y: -20 - self.tipLabelHeight, width: UIScreen.mainScreen().bounds.width, height: self.tipLabelHeight)
        
        return label
    }()
    
}

// MARK: - 扩展YGHomeViewController，tableView显示数据
extension YGHomeViewController {
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        // 判断有没有缓存行高
        // 获取对应模型
        let status = self.statuses![indexPath.row]
        
        if let rowHeight = status.rowHeight {
            // 有缓存行高
            YGPrint(items: "有缓存行高: \(rowHeight), row: \(indexPath.row)")
            return rowHeight
        }
        
        // 没有行高执行下面
        // 自己计算行高
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseIndentifier) as! YGStatusCell
        cell.status = status
        
        // 获取行高
        let height = cell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
        // 缓存计算好的行高
        status.rowHeight = height
//        YGPrint(items: "计算行高: \(height), row: \(indexPath.row)")
        
        return height
    }
    
    // 返回有几行
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    // cell 的内容
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueReusableCellWithIdentifier(reuseIndentifier, forIndexPath: indexPath) as! YGStatusCell
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseIndentifier) as! YGStatusCell
        
        // 获取对应模型
        let status = statuses![indexPath.row]
        
//        cell.textLabel?.text = status.text
        // 赋值
        cell.status = status
        
        return cell
    }
    
}
















